package com.estun.backroundManagementService.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.estun.backroundManagementService.config.factoryMes.ApiCaller;
import com.estun.backroundManagementService.config.properties.ApiInfoProperties;
import com.estun.backroundManagementService.config.properties.LineInfoProperties;
import com.estun.backroundManagementService.domain.factoryMes.request.PassStationRequest;
import com.estun.backroundManagementService.domain.factoryMes.request.PushAlarmRequest;
import com.estun.backroundManagementService.domain.factoryMes.request.PushDeviceStatusRequest;
import com.estun.backroundManagementService.domain.factoryMes.request.base.BaseMesRequest;
import com.estun.backroundManagementService.domain.factoryMes.request.base.BaseMesResponse;
import com.estun.backroundManagementService.enums.FactoryMesDeviceStatusEnum;
import com.estun.backroundManagementService.modules.alarm.model.StationAlarm;
import com.estun.backroundManagementService.modules.alarm.model.StationAlarmMapping;
import com.estun.backroundManagementService.modules.alarm.service.StationAlarmService;
import com.estun.backroundManagementService.modules.device.model.DeviceStatus;
import com.estun.backroundManagementService.modules.device.service.DeviceStatusService;
import com.estun.backroundManagementService.modules.position.service.DeviceService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yusiocng
 * @date 2023/12/19
 * @description 推送定时任务
 */

@Slf4j
@Component
@AllArgsConstructor
@Profile("prd")
public class PushDeviceStatusTask {

    private final ApiCaller apiCaller;
    private final ApiInfoProperties apiInfoProperties;
    private final DeviceStatusService deviceStatusService;
    private final DeviceService deviceService;

    /**
     * 推送 设备状态
     */
    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void pushDeviceStatus() {
        List<DeviceStatus> allList = deviceStatusService.list();
        List<DeviceStatus> toBePushList = new ArrayList<>();
        for (DeviceStatus deviceStatus : allList) {
            //推送时间为空 一次未推送的
            if (deviceStatus.getSubmitTime() == null) {
                toBePushList.add(deviceStatus);
            }
            //更新时间在推送时间之后的
            else if (deviceStatus.getUpdateTime().isAfter(deviceStatus.getSubmitTime())) {
                toBePushList.add(deviceStatus);
            }
        }
        if (CollectionUtils.isEmpty(toBePushList)) {
            log.info("【推送设备状态】,本次没有待推送数据，任务结束");
            return;
        }
        int toBePushSize = toBePushList.size();
        log.info("【推送设备状态】本次待推送数据:{}条", toBePushSize);
        int failNumber = 0;
        for (DeviceStatus deviceStatus : toBePushList) {
            BaseMesRequest<PushDeviceStatusRequest> mesRequest = new BaseMesRequest<>();
            PushDeviceStatusRequest passStationRequest = buildPushDeviceStatusData(deviceStatus);
            mesRequest.setData(Collections.singletonList(passStationRequest));
            BaseMesResponse mesResponse = apiCaller.post(apiInfoProperties.getPushEquipmentStatus(), mesRequest, BaseMesResponse.class);
            //更新推送状态
            if (mesResponse.isSuccess()) {
                deviceStatus.setSubmitStatus(1);
                deviceStatus.setSubmitTime(LocalDateTime.now());
            } else {
                log.error("【推送设备状态】推送失败 工厂MES返回:{}", mesResponse);
                deviceStatus.setSubmitStatus(-1);
                failNumber++;
            }
            deviceStatus.setSubmitNumber(deviceStatus.getSubmitNumber() + 1);
            deviceStatusService.updateById(deviceStatus);
        }
        log.info("【推送设备状态】任务结束，本次任务数量：{},成功数量:{},失败数量:{}", toBePushSize, toBePushSize - failNumber, failNumber);
    }

    /**
     * 构造设备状态推送requestBody
     */
    private PushDeviceStatusRequest buildPushDeviceStatusData(DeviceStatus deviceStatus) {
        PushDeviceStatusRequest req = new PushDeviceStatusRequest();
        String stationId = deviceStatus.getStationId();
        String deviceCode = deviceService.getDeviceCodeByStationId(stationId);
        //todo 机台编码 需要比亚迪提供对照表
        req.setMachineCode(deviceCode);
        req.setStationCode(stationId);
        req.setMachineStatusCode(FactoryMesDeviceStatusEnum.getByDeviceStatus(deviceStatus.getAlarmName()).getCode());
        //todo 数采设备编码 需要比亚迪提供对照表
        req.setAcquisitCode(deviceCode);
        req.setMachineStatusBegin(deviceStatus.getUpdateTime());
        req.setMachineStatusEnd(deviceStatus.getUpdateTime());
        req.setEditTime(deviceStatus.getUpdateTime());
        req.setStatusType(deviceStatus.getStatus() == 1 ? 0 : 1);
        // 故障No push
        // PushDeviceStatusRequest.Failure failureList
        return req;
    }




}
